/* eslint-disable no-mixed-spaces-and-tabs */
/* eslint-disable no-mixed-spaces-and-tabs */
<template>
  <el-dialog
    :title="!dataForm.id ? '新增用户' : '修改用户'"
    :close-on-click-modal="false"
    width="60%"
    :visible.sync="visible"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="80px" @keyup.enter.native="dataFormSubmit()">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="员工照片" size="mini" prop="staffPhoto" class="unbuttom">
            <!-- <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              accept="image/png,image/gif,image/jpg,image/jpeg"

              :action="uploadUrl"
              :with-credentials="true"
            >
              <img v-if="dataForm.staffPhoto" :src="dataForm.staffPhoto" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload> -->
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item size="mini" label="用户名" prop="Username">
            <el-input v-model="dataForm.Username" maxlength="25" show-word-limit placeholder="请输入登录帐号" />
          </el-form-item>
          <el-form-item size="mini" label="员工姓名" prop="Name">
            <el-input v-model="dataForm.Name" maxlength="25" show-word-limit placeholder="请输入员工姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size="mini" label="电子邮箱" prop="Email">
            <el-input v-model="dataForm.Email" maxlength="50" show-word-limit placeholder="请输入工作电子邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size="mini" label="联系电话" prop="Phone">
            <el-input v-model="dataForm.Phone" maxlength="20" placeholder="请输入工作电话号码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="系统编码" size="mini" prop="Staffno">
            <el-input v-model="dataForm.Staffno" readonly placeholder="工号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属租户" size="mini">
            <el-select
              v-model="dataForm.Tenant"
              default-first-option
              clearable
              filterable
              remote
              reserve-keyword
              style="width: 100%"
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="tenantselect.loading"
            >
              <el-option
                v-for="item in tenantselect.options"
                :key="item.Code"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size="mini" label="所属组织" prop="Org">
            <el-popover
              ref="orgListPopover"
              v-model="orgtree.orgVisible"
              placement="bottom-start"
              trigger="click"
              :width="orgtree.popwidth"
              @show="getPopover('org_input','orgListPopover')"
            >
              <div style="height: 200px; display: block; display: 100%; overflow-y:auto">
                <el-tree
                  ref="menuListTree"
                  :data="orgtree.orgValidLst"
                  :props="orgtree.orgListTreeProps"
                  node-key="id"
                  :default-expand-all="false"
                  :highlight-current="true"
                  :expand-on-click-node="false"
                  @current-change="orgListTreeCurrentChangeHandle"
                />
              </div>
            </el-popover>
            <el-input
              ref="org_input"
              v-model="dataForm.OrgName"
              v-popover:orgListPopover
              :readonly="true"
              placeholder="点击选择组织机构"
              class="menu-list__input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size="mini" label="所在职位" prop="Position">
            <el-popover
              ref="positionListPopover"
              v-model="positiontree.positionVisible"
              :width="positiontree.popwidth"
              trigger="click"
              placement="bottom-start"
              @show="getPopover('position_input','positionListPopover')"
            >
              <div style="height: 200px;width:100%;overflow-y:auto">
                <el-tree
                  ref="positionList"
                  :data="positiontree.positionList"
                  :props="positiontree.positionTreeProps"
                  node-key="id"
                  :default-expand-all="false"
                  :highlight-current="true"
                  :expand-on-click-node="false"
                  @current-change="positionListTreeCurrentChangeHandle"
                />
              </div>
            </el-popover>
            <el-input
              ref="position_input"
              v-model="dataForm.PositionName"
              v-popover:positionListPopover
              :readonly="true"
              placeholder="点击选择岗位"
              class="menu-list__input"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col style="text-align: right;">
        <el-button size="mini" icon="el-icon-close" @click="visible = false">取消</el-button>
        <el-button size="mini" icon="el-icon-check" type="primary" @click="dataFormSubmit()">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { validEmail } from '@/utils/validate'
import { fetchAll } from '@/api/tenant'
import { getUser, saveUser, updateUser } from '@/api/user'
import { fetchList as orgfetchlist } from '@/api/org'
import { fetchList as positionfetchlist } from '@/api/position'
// eslint-disable-next-line no-unused-vars
import { treeDataTranslate, treeToArrayList, getChildNodeFromArray } from '@/utils'
export default {
  data() {
    var validateUserEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('用户邮箱格式错误'))
      } else {
        callback()
      }
    }
    return {
      // 是否显示
      visible: false,
      // 校验规则
      dataRule: {
        Username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        Name: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' }
        ],
        Email: [
          { required: true, message: '员工电子邮箱不能为空', trigger: 'blur' },
          { validator: validateUserEmail, trigger: 'blur' }
        ],
        Phone: [
          { required: true, message: '员工联系电话不能为空', trigger: 'blur' }
        ]
      },
      // 租户下拉框设置
      tenantselect: {
        options: [],
        list: [],
        loading: false,
        orgfetchlist
      },

      // 组织结构 树形菜单设置
      orgtree: {
        orgVisible: false,
        popwidth: 150,
        orgValidLst: [],
        list: [],
        orgListTreeProps: {
          label: 'Name',
          children: 'children'
        }
      },

      // 岗位设置 树形菜单设置
      positiontree: {
        positionVisible: false,
        popwidth: 150,
        positionList: [],
        positionTreeProps: {
          label: 'Name',
          children: 'children'
        },
        list: []
      },

      // 用户model
      dataForm: {
        Id: '',
        Name: '',
        Username: '',
        Phone: '',
        Email: '',
        Staffnum: '',
        OrgName: '',
        Tenant: '',
        Orgid: '',
        Positionid: '',
        PositionName: ''
      }
    }
  },
  methods: {
    getPopover(container, popover) {
      const me = this
      // 设置组织
      if (container === 'org_input') {
        me.orgtree.orgVisible = true
        me.orgtree.popwidth = me.$refs[container].$el.offsetWidth
        return false
      }
      // 设置岗位
      if (container === 'position_input') {
        me.positiontree.positionVisible = true
        me.positiontree.popwidth = me.$refs[container].$el.offsetWidth
        return false
      }
    },
    // 组织结构选中
    orgListTreeCurrentChangeHandle(data, node) {
      this.dataForm.Orgid = data.Id
      this.dataForm.OrgName = data.Name
      this.orgtree.orgVisible = false
    },
    // 职位选中
    positionListTreeCurrentChangeHandle(data, node) {
      this.dataForm.Positionid = data.Id
      this.dataForm.PositionName = data.Name
      this.positiontree.positionVisible = false
    },
    // 初始化
    init(id, tenant) {
      this.visible = true
      this.clearDataForm()
      this.dataForm.Id = id || 0
      // 获取组织结构
      orgfetchlist().then((data) => {
        if (data && data.code === '20000') {
          this.orgtree.list = data.data
          this.orgtree.orgValidLst = treeDataTranslate(this.orgtree.list, 'Id', 'Parentid')
        }
      }).then(() => {
        // 获取职位
        positionfetchlist().then((data) => {
          if (data && data.code === '20000') {
            this.positiontree.list = data.data
            this.positiontree.positionList = treeDataTranslate(this.positiontree.list, 'Id', 'Parentid')
          }
        }).then(() => {
        // 获取租户
          fetchAll().then((data) => {
            if (data && data.code === '20000') {
              const result = data.data
              this.tenantselect.list = result
              this.tenantselect.options = this.tenantselect.list
              this.dataForm.Tenant = tenant
            }
          }).then(() => {
            if (id && id > 0) {
              getUser(id).then((data) => {
                if (data && data.code === '20000') {
                  this.dataForm.Id = data.user.Id
                  this.dataForm.Name = data.user.Name
                  this.dataForm.Username = data.user.Username
                  this.dataForm.Phone = data.user.Phone
                  this.dataForm.Email = data.user.Email
                  this.dataForm.Tenant = data.user.Tenant
                  this.dataForm.Staffno = data.user.Staffnum
                  this.dataForm.Orgid = data.user.Orgid
                  this.dataForm.Positionid = data.user.Positionid
                  if (this.dataForm.Orgid && this.dataForm.Orgid > 0) {
                    const re = this.orgtree.list.filter(r => r.Id === this.dataForm.Orgid)
                    if (re) {
                      this.dataForm.OrgName = re[0].Name
                    } else {
                      this.dataForm.OrgName = ''
                    }
                  }
                  if (this.dataForm.Positionid && this.dataForm.Positionid > 0) {
                    const plist = this.positiontree.list.filter(r => r.Id === this.dataForm.Positionid)
                    if (plist && plist.length > 0) {
                      this.dataForm.PositionName = plist[0].Name
                    } else {
                      this.dataForm.PositionName = ''
                    }
                  }
                }
              })
            }
          })
        })
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.tenantselect.loading = true
        setTimeout(() => {
          this.tenantselect.loading = false
          this.tenantselect.options = this.tenantselect.list.filter(item => {
            return item.Name.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
                item.Code.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200
        )
      } else {
        this.tenantselect.options = this.tenantselect.list
      }
    },
    clearDataForm() {
      this.dataForm.Id = 0
      this.dataForm.Username = ''
      this.dataForm.Phone = ''
      this.dataForm.Name = ''
      this.dataForm.Email = ''
      this.dataForm.Tenant = ''
      this.dataForm.Staffno = ''
      this.dataForm.Orgid = ''
      this.dataForm.OrgName = ''
      this.dataForm.Positionid = ''
      this.dataForm.PositionName = ''
    },
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var data = {
            'Id': this.dataForm.Id || undefined,
            'Username': this.dataForm.Username,
            'Email': this.dataForm.Email,
            'Phone': this.dataForm.Phone,
            'staffstatus': this.dataForm.Status,
            'Name': this.dataForm.Name,
            'Tenant': this.dataForm.Tenant === '' ? null : this.dataForm.Tenant,
            'Staffnum': this.dataForm.Staffno,
            'Orgid': this.dataForm.Orgid === '' ? null : this.dataForm.Orgid,
            'Positionid': this.dataForm.Positionid === '' ? null : this.dataForm.Positionid
          }
          var permission
          if (this.dataForm.Id && this.dataForm.Id > 0) {
            permission = updateUser(data)
          } else {
            permission = saveUser(data)
          }
          permission.then((data) => {
            if (data && data.code === '20000') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.message)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .unbuttom{
    margin-bottom: 0px !important
  }
</style>
